package com.gs.disk.controller.admin;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.gs.entity.GeneralPage;
import com.gs.entity.R;
import com.gs.common.exception.RenException;
import com.gs.common.util.ConvertUtils;
import com.gs.common.util.JWTUtil;
import com.gs.common.util.SecurityUtils;
import com.gs.disk.dto.admin.UserDto;

import com.gs.disk.service.admin.UserService;
import com.gs.disk.service.common.RoleService;
import com.gs.entity.UserEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("disk/admin/user")
@Api(tags = "后台登录")
@ApiSort(3)
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    @GetMapping("getUserList")
    @ApiOperation("获取用户列表")
    @RequiresPermissions({"sys:user:list"})
    public R<GeneralPage<UserDto>> getUserList(@RequestParam Map<String, Object> map) {
        GeneralPage<UserDto> userList = userService.getUserList(map);
        return R.ok(userList);
    }


    @GetMapping("/getUserInfo")
    @ApiOperation("获取用户信息")
    @RequiresPermissions({"sys:user:info"})
    public R<UserDto> getUserInfo() {
        UserEntity user = SecurityUtils.getUser();
        UserDto userDto = ConvertUtils.sourceToTarget(user, UserDto.class);
        // 获取用户角色
        List<String> roleName = roleService.roleNameList(user.getId());
        userDto.setRoleNameList(roleName);
        // 获取用户菜单
        List<String> menuList = userService.getUserMenuList(userDto.getName());
        userDto.setMenus(menuList);
        // 获取用户权限
        Set<String> rolePermissionSet = userService.getUserRolePermission(userDto.getName());
        userDto.setPermissions(rolePermissionSet);
        return R.ok(userDto);
    }


    @PostMapping("/login")
    @ApiOperation("用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名",paramType = "body"),
            @ApiImplicitParam(name = "password", value = "密码", paramType = "body") // 这块有坑,paramType不给值swagger会报错
    })
    public R login(@RequestBody @ApiIgnore Map<String, String> map) {
        String username = map.get("username");
        String password = map.get("password"); // 正确密码
        String password2 = userService.getPassword(username); // 数据库加密后的密码

        // 如果用户不存在的情况下, 那么密码就更不可能存在了
        if(ObjectUtil.isNull(password2)) {
            return new R().error("用户名或密码错误");
        }
        // 检查密码是否正确
        boolean check = BCrypt.checkpw(password, password2);

        // 密码不正确
        if (!check) {
           return new R().error("用户名或密码错误");
        } else {
            return new R().ok(JWTUtil.createToken(username));
        }

    }



    /**
     * 修改，修改所有字段
     *
     * @param user 修改的记录
     * @return 返回影响行数
     */
    @PostMapping("/update")
    public R update(@RequestBody UserEntity user) {
        userService.save(user);
        return new R();
    }

    /**
     * 修改用户权限
     *
     * @param permissionList 权限列表
     * @return 返回影响行数
     */
    @PostMapping("/updatePermissions")
    @ApiOperation("修改用户权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "permissionList", value = "权限列表",paramType = "body"),
    })
    public R updatePermissions(@RequestBody List<String> permissionList) {
        Long userId = SecurityUtils.getUserId();
        userService.updatePermissions(userId, permissionList);
        return new R();
    }

    /**
     * 修改用户权限
     *
     * @param permissionList 权限列表
     * @return 返回影响行数
     */
    @PutMapping("/updatePermissions/{userId}")
    @ApiOperation("根据userId修改用户权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "permissionList", value = "权限列表",paramType = "body"),
    })
    public R updatePermissionsByUserId(@PathVariable Long userId, @RequestBody List<String> permissionList) {
        userService.updatePermissions(userId, permissionList);
        return new R();
    }
    /**
     * 删除用户
     *
     * @param id 待删除的用户id
     * @return 返回影响行数
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除用户")
    @RequiresPermissions({"sys:user:delete"})
    public R delete(@PathVariable Long id) {

        List<String> roleNameList = roleService.roleNameList(id);

        if(CollectionUtil.contains(roleNameList, "平台管理员")) {
            throw new RenException("平台管理员无法删除");
        }
        userService.delete(id);
        return new R();
    }

}